package com.youlai.netty.service.tcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理心跳包
 * @author zc
 * @date 2023-02-02 00:08
 */
@Slf4j
public class PingPangHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if(event.state() == IdleState.WRITER_IDLE){
                log.info("有一段时间没写入数据了");
            }else if(event.state() == IdleState.READER_IDLE){
              log.info("有一段时间没读到数据了");
            }else if(event.state() == IdleState.ALL_IDLE){
                log.info("有一段时间没读写到数据了");
            }
        }else{
        super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MyMessageProtocol data = (MyMessageProtocol) msg;
      if(data.getBody().equals("pingPang")){
          log.info("收到心跳包数据");
      }else{
          log.info("不是心跳包,传递给下一个handler");
          ctx.fireChannelRead(msg);
      }
    }
}
